//
//  DBPictureView.swift
//  大波微博swift
//
//  Created by 大波 on 16/3/5.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import SDWebImage

/// 最大列数
private var maxCol = 3

/// item个数
private var itemCount = 0

/// 间隔
private let margin = 8

/// item宽高
private var itemWidth = (UIScreen.width - CGFloat(4 * margin) - CGFloat((maxCol - 1) * margin)) / CGFloat(maxCol)

private var itemSize = CGSize(width: itemWidth, height: itemWidth)

class DBPictureView: UICollectionView {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var pictureData: [[String : AnyObject]]? {
        
        didSet {
            
            if let data = pictureData {
                
                itemCount = data.count
            }
        }
    }
    
    private let reuseIdentifier = "reuseIdentifier"
    
    private let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    
    var statuse: DBStatuses? {
        
        didSet {
            
            pictureData = statuse?.pic_urls
            
            var viewSize = calculateSize()
            
            viewSize = CGSize(width: viewSize.width + 2, height: viewSize.height + 2)
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.size.equalTo(viewSize)
            }
            
            reloadData()
        }
    }
    
    private func calculateSize() -> CGSize {
        
        if itemCount == 0 {
            
            return CGSizeZero
        }
        
        if itemCount == 1 {
            
            var size = CGSize(width: 180, height: 120)
            
            // 获取图片URL
            let url = statuse?.picDataURL?.first?.absoluteString
            
            // 从缓存获取图片
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url) {
                
                size = image.size
            }
            
            // 太小或太大情况
            if size.width < 40 {
                
                size.width = 40
                
            } else if size.width > UIScreen.width * 0.5 {
                
                size.width = UIScreen.width * 0.5
            }
            
            layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
            
            layout.minimumLineSpacing = 0
            
            layout.minimumInteritemSpacing = 0
            
            return itemSize
        }
        
        layout.itemSize = itemSize
        
        if itemCount == 2 || itemCount == 4 {
            
            return CGSize(width: CGFloat(2 * itemWidth) + CGFloat(margin), height: itemCount == 2 ? itemWidth : itemWidth * 2 + CGFloat(margin))
        }
        
        layout.minimumLineSpacing = CGFloat(margin)
        
        layout.minimumInteritemSpacing = CGFloat(margin)
        
        // 宽度  都是三个item  高度 两个三目  一个三目判断是否是三个item   是就一个item高度   最后那个三目是判断item是否小于6个 小于则两个item高度
        return CGSize(width: CGFloat(itemWidth * 3) + CGFloat(margin * 2), height: itemCount == 3 ? CGFloat(itemWidth) : itemCount <= 6 ? CGFloat(itemWidth * 2) + CGFloat(margin) : CGFloat(itemWidth * 3) + CGFloat(margin * 2))
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: CGRectZero, collectionViewLayout: self.layout)
        
        registerClass(DBPictureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        dataSource = self
        
        backgroundColor = UIColor.whiteColor()
    }
}

// MARK: - UICollectionViewDataSource

extension DBPictureView: UICollectionViewDataSource {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureData?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! DBPictureViewCell
        
        cell.pictureData = statuse?.picDataURL?[indexPath.item]
        
        return cell
    }
}

// MARK: - UICollectionViewCell

class DBPictureViewCell: UICollectionViewCell {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var pictureData: NSURL? {
        
        didSet {
            
            bgView.sd_setImageWithURL(pictureData)
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        
        contentView.addSubview(bgView)
        
        bgView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.bottom.equalTo(contentView)
        }
        
        bgView.contentMode = UIViewContentMode.ScaleAspectFill
        
        bgView.clipsToBounds = true
    }
    // MARK: - 懒加载
    
    /// 图片
    private lazy var bgView: UIImageView = UIImageView(image: nil)
}

























